<template>
  <view class="materials-filter">
    <!-- 筛选面板头部 -->
    <view class="filter-header" @click="toggleFilterPanel">
      <view class="filter-header-left">
        <wd-icon name="filter" size="16px" color="#007AFF" />
        <text class="filter-title">筛选条件</text>
        <view v-if="hasActiveFilters" class="filter-active-dot" />
      </view>
      <view class="filter-header-right">
        <wd-button type="text" size="small" class="reset-button" @click.stop="resetFilters">
          重置
        </wd-button>
        <wd-icon
          :name="showFilterPanel ? 'arrow-up' : 'arrow-down'"
          size="16px"
          color="#8E8E93"
          class="collapse-icon"
        />
      </view>
    </view>

    <!-- 筛选面板内容 -->
    <view v-show="showFilterPanel" class="filter-content">
      <!-- 仓库筛选 -->
      <view v-if="showWarehouse" class="filter-row">
        <view class="filter-item">
          <WarehouseSelect
            v-model="internalFilters.warehouseId"
            placeholder="选择仓库"
            @change="handleWarehouseChange"
          />
        </view>
      </view>

      <!-- 标签筛选 -->
      <view v-if="showTags" class="filter-row">
        <view class="filter-item">
          <TagSelect
            v-model="internalFilters.tagIds"
            :multiple="true"
            placeholder="选择标签"
            @change="handleTagChange"
          />
        </view>
      </view>

      <!-- 搜索筛选 -->
      <view v-if="showSearch" class="filter-row">
        <view class="filter-item">
          <view class="search-input-wrapper">
            <!-- 融合式搜索输入框 -->
            <view class="integrated-search-container">
              <!-- 搜索类型选择按钮 -->
              <view class="search-type-button" @click="showSearchTypePicker = true">
                <text class="search-type-label">{{ currentSearchType.label }}</text>
                <wd-icon name="arrow-down" size="10px" color="#8E8E93" />
              </view>

              <!-- 分割线 -->
              <view class="search-divider" />

              <!-- 搜索输入框区域 -->
              <view class="search-input-section">
                <wd-icon name="search" size="16px" color="#8E8E93" class="search-icon" />
                <input
                  v-model="internalFilters.searchText"
                  :placeholder="`输入${currentSearchType.label}`"
                  class="search-input"
                  @input="handleSearchInput"
                  @keydown.enter="handleSearch"
                />

                <!-- 内置搜索按钮 -->
                <view class="inline-search-button" @click="handleSearch">
                  <wd-icon name="search" size="14px" color="#007AFF" />
                </view>

                <view v-if="internalFilters.searchText" class="clear-button" @click="clearSearch">
                  <wd-icon name="close-circle-fill" size="16px" color="#C7C7CC" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 自定义筛选项 -->
      <slot name="custom-filters" :filters="internalFilters" />
    </view>
  </view>

  <!-- 搜索类型选择弹窗 - 移到组件外部 -->
  <wd-popup
    v-model="showSearchTypePicker"
    position="bottom"
    :close-on-click-modal="true"
    :safe-area-inset-bottom="true"
    :z-index="9999"
    class="search-type-popup"
  >
    <view class="popup-header">
      <text class="popup-title">选择搜索类型</text>
      <wd-button type="text" size="small" @click="showSearchTypePicker = false">完成</wd-button>
    </view>
    <view class="search-type-list">
      <view
        v-for="type in searchTypes"
        :key="type.value"
        class="search-type-item"
        :class="{ active: internalFilters.searchType === type.value }"
        @click="handleSearchTypeChange(type.value)"
      >
        <view class="type-info">
          <text class="type-label">{{ type.label }}</text>
          <text class="type-desc">{{ type.description }}</text>
        </view>
        <text v-if="internalFilters.searchType === type.value" class="check-mark">✓</text>
      </view>
    </view>
  </wd-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
// 组件会通过全局注册或者自动导入的方式使用，无需显式导入

interface FilterParams {
  warehouseId?: number
  tagIds?: number[]
  searchType?: string
  searchText?: string
  productName?: string
  productNumber?: string
  [key: string]: any
}

interface Props {
  /** 筛选参数 */
  modelValue?: FilterParams
  /** 是否显示仓库筛选 */
  showWarehouse?: boolean
  /** 是否显示标签筛选 */
  showTags?: boolean
  /** 是否显示搜索功能 */
  showSearch?: boolean
  /** 默认是否展开 */
  defaultExpanded?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({}),
  showWarehouse: true,
  showTags: true,
  showSearch: true,
  defaultExpanded: true,
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: FilterParams): void
  (e: 'search'): void
  (e: 'reset'): void
  (e: 'warehouse-change', value: number | number[]): void
  (e: 'tag-change', value: number | number[]): void
}>()

// 状态管理
const showFilterPanel = ref(props.defaultExpanded)
const showSearchTypePicker = ref(false)

// 搜索类型配置
const searchTypes = [
  {
    value: 'name',
    label: '名称',
    description: '按物资名称搜索',
    field: 'productName',
  },
  {
    value: 'number',
    label: '编号',
    description: '按物资编号搜索',
    field: 'productNumber',
  },
]

// 内部筛选参数
const internalFilters = ref<FilterParams>({
  warehouseId: undefined,
  tagIds: [],
  searchType: 'name',
  searchText: '',
  productName: '',
  productNumber: '',
  ...props.modelValue,
})

// 计算属性
const currentSearchType = computed(() => {
  return (
    searchTypes.find((type) => type.value === internalFilters.value.searchType) || searchTypes[0]
  )
})

const hasActiveFilters = computed(() => {
  const filters = internalFilters.value
  return !!(
    filters.warehouseId ||
    (filters.tagIds && filters.tagIds.length > 0) ||
    filters.searchText ||
    filters.productName ||
    filters.productNumber
  )
})

// 监听外部参数变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      internalFilters.value = {
        ...internalFilters.value,
        ...newVal,
      }
    }
  },
  { deep: true },
)

// 监听内部参数变化，同步到外部
watch(
  internalFilters,
  (newVal) => {
    emit('update:modelValue', { ...newVal })
  },
  { deep: true },
)

// 事件处理
function toggleFilterPanel() {
  showFilterPanel.value = !showFilterPanel.value
}

function handleWarehouseChange(value: number | number[]) {
  internalFilters.value.warehouseId = Array.isArray(value) ? value[0] : value
  emit('warehouse-change', value)
  emit('search')
}

function handleTagChange(value: number | number[]) {
  internalFilters.value.tagIds = Array.isArray(value) ? value : [value]
  emit('tag-change', value)
  emit('search')
}

function handleSearchTypeChange(type: string) {
  internalFilters.value.searchType = type
  showSearchTypePicker.value = false

  // 清空之前的搜索内容
  internalFilters.value.productName = ''
  internalFilters.value.productNumber = ''

  // 如果有搜索文本，重新处理
  if (internalFilters.value.searchText) {
    handleSearchInput()
  }
}

function handleSearchInput() {
  const text = internalFilters.value.searchText?.trim() || ''
  const searchType = currentSearchType.value

  // 清空所有搜索字段
  internalFilters.value.productName = ''
  internalFilters.value.productNumber = ''

  // 根据搜索类型设置对应字段
  if (text && searchType.field) {
    internalFilters.value[searchType.field] = text
  }
}

function handleSearch() {
  handleSearchInput()
  emit('search')
}

function clearSearch() {
  internalFilters.value.searchText = ''
  internalFilters.value.productName = ''
  internalFilters.value.productNumber = ''
  emit('search')
}

function resetFilters() {
  internalFilters.value = {
    warehouseId: undefined,
    tagIds: [],
    searchType: 'name',
    searchText: '',
    productName: '',
    productNumber: '',
  }
  emit('reset')
  emit('search')
}

// 暴露方法给父组件
defineExpose({
  resetFilters,
  getFilters: () => internalFilters.value,
  setFilters: (filters: FilterParams) => {
    internalFilters.value = { ...internalFilters.value, ...filters }
  },
})

// 定义组件名称
defineOptions({
  name: 'MaterialsFilter',
})
</script>

<style lang="scss" scoped>
// Apple设计系统变量
$system-blue: #007aff;
$system-red: #ff3b30;
$system-gray: #8e8e93;
$label-primary: #000000;
$label-secondary: rgba(60, 60, 67, 0.6);
$background-primary: #ffffff;
$background-secondary: #f2f2f7;
$separator: rgba(60, 60, 67, 0.36);

.materials-filter {
  background: $background-primary;
  border-radius: 16px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.1);
  /* 移除可能导致层叠上下文限制的属性 */

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: rgba(0, 122, 255, 0.05);
    border-bottom: 1px solid rgba(0, 122, 255, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;

    &:active {
      background: rgba(0, 122, 255, 0.1);
    }

    .filter-header-left {
      display: flex;
      align-items: center;
      gap: 10px;
      position: relative;

      .filter-title {
        font-size: 17px;
        font-weight: 600;
        color: $label-primary;
        letter-spacing: -0.2px;
      }

      .filter-active-dot {
        width: 8px;
        height: 8px;
        background: linear-gradient(45deg, $system-blue, #34c759);
        border-radius: 50%;
        margin-left: 8px;
        box-shadow: 0 2px 4px rgba(0, 122, 255, 0.3);
        animation: pulse 2s infinite;

        @keyframes pulse {
          0%,
          100% {
            transform: scale(1);
            opacity: 1;
          }
          50% {
            transform: scale(1.2);
            opacity: 0.8;
          }
        }
      }
    }

    .filter-header-right {
      display: flex;
      align-items: center;
      gap: 12px;

      .reset-button {
        padding: 4px 12px;
        background: linear-gradient(135deg, rgba(255, 59, 48, 0.1) 0%, rgba(255, 149, 0, 0.1) 100%);
        border: 1px solid rgba(255, 59, 48, 0.2);
        border-radius: 14px;
        color: $system-red;
        font-size: 13px;
        font-weight: 500;
        transition: all 0.2s ease;

        &:active {
          background: linear-gradient(
            135deg,
            rgba(255, 59, 48, 0.2) 0%,
            rgba(255, 149, 0, 0.2) 100%
          );
          transform: scale(0.95);
        }
      }

      .collapse-icon {
        transition: all 0.3s ease;
      }
    }
  }

  .filter-content {
    padding: 20px;
    animation: filterExpand 0.3s ease;

    @keyframes filterExpand {
      from {
        opacity: 0;
        max-height: 0;
      }
      to {
        opacity: 1;
        max-height: 500px;
      }
    }
  }

  .filter-row {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .filter-item {
      .filter-label {
        display: block;
        font-size: 14px;
        font-weight: 600;
        color: $label-primary;
        margin-bottom: 8px;
      }

      .search-input-wrapper {
        .integrated-search-container {
          display: flex;
          align-items: stretch;
          background: $background-primary;
          border: 2px solid rgba(0, 122, 255, 0.1);
          border-radius: 16px;
          overflow: hidden;
          transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

          &:hover {
            border-color: rgba(0, 122, 255, 0.2);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
          }

          &:focus-within {
            border-color: $system-blue;
            box-shadow: 0 0 0 4px rgba(0, 122, 255, 0.1);
          }

          .search-type-button {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 14px 16px;
            background: linear-gradient(
              135deg,
              rgba(0, 122, 255, 0.05) 0%,
              rgba(52, 199, 89, 0.03) 100%
            );
            border-right: 1px solid rgba(0, 122, 255, 0.1);
            cursor: pointer;
            transition: all 0.2s ease;
            min-width: 70px;
            justify-content: center;

            &:active {
              background: linear-gradient(
                135deg,
                rgba(0, 122, 255, 0.1) 0%,
                rgba(52, 199, 89, 0.06) 100%
              );
              transform: scale(0.98);
            }

            .search-type-label {
              font-size: 13px;
              font-weight: 600;
              color: $system-blue;
              white-space: nowrap;
              letter-spacing: -0.1px;
            }
          }

          .search-divider {
            width: 1px;
            background: linear-gradient(
              180deg,
              transparent 0%,
              rgba(0, 122, 255, 0.2) 50%,
              transparent 100%
            );
            margin: 8px 0;
          }

          .search-input-section {
            flex: 1;
            display: flex;
            align-items: center;
            padding: 0 16px;
            gap: 12px;
            position: relative;

            .search-icon {
              flex-shrink: 0;
              opacity: 0.6;
            }

            .search-input {
              flex: 1;
              border: none;
              outline: none;
              font-size: 16px;
              color: $label-primary;
              background: transparent;
              padding: 14px 0;
              font-weight: 400;
              letter-spacing: -0.1px;

              &::placeholder {
                color: rgba(142, 142, 147, 0.8);
                font-weight: 400;
              }

              &:focus {
                &::placeholder {
                  opacity: 0.5;
                }
              }
            }

            .inline-search-button {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 32px;
              height: 32px;
              background: linear-gradient(
                135deg,
                rgba(0, 122, 255, 0.1) 0%,
                rgba(52, 199, 89, 0.08) 100%
              );
              border-radius: 16px;
              cursor: pointer;
              transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
              flex-shrink: 0;
              border: 1px solid rgba(0, 122, 255, 0.2);

              &:hover {
                background: linear-gradient(
                  135deg,
                  rgba(0, 122, 255, 0.15) 0%,
                  rgba(52, 199, 89, 0.12) 100%
                );
                transform: scale(1.05);
              }

              &:active {
                transform: scale(0.95);
                background: linear-gradient(
                  135deg,
                  rgba(0, 122, 255, 0.2) 0%,
                  rgba(52, 199, 89, 0.15) 100%
                );
              }
            }

            .clear-button {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 24px;
              height: 24px;
              border-radius: 12px;
              cursor: pointer;
              transition: all 0.2s ease;
              flex-shrink: 0;

              &:active {
                transform: scale(0.9);
                background: rgba(199, 199, 204, 0.2);
              }
            }
          }
        }
      }
    }
  }
}

// 搜索类型选择弹窗
.search-type-popup {
  // 确保弹窗在最上层
  :deep(.wd-popup) {
    z-index: 9999 !important;
  }

  :deep(.wd-popup__mask) {
    z-index: 9998 !important;
  }

  :deep(.wd-popup__content) {
    z-index: 9999 !important;
  }

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid rgba(0, 122, 255, 0.1);
    background: linear-gradient(135deg, rgba(0, 122, 255, 0.05) 0%, rgba(52, 199, 89, 0.03) 100%);
    backdrop-filter: blur(20px);
    border-radius: 16px 16px 0 0;

    .popup-title {
      font-size: 17px;
      font-weight: 600;
      color: $label-primary;
      letter-spacing: -0.3px;
    }
  }

  .search-type-list {
    background: $background-primary;
    max-height: 40vh;
    overflow-y: auto;
    padding-bottom: calc(env(safe-area-inset-bottom) + 20px);

    .search-type-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 18px 24px;
      border-bottom: 1px solid rgba(0, 122, 255, 0.08);
      transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
      cursor: pointer;

      &:active {
        background: rgba(0, 122, 255, 0.1);
        transform: scale(0.98);
      }

      &.active {
        background: linear-gradient(
          135deg,
          rgba(0, 122, 255, 0.1) 0%,
          rgba(52, 199, 89, 0.08) 100%
        );
        border-left: 4px solid $system-blue;
        padding-left: 20px;
      }

      &:last-child {
        border-bottom: none;
      }

      .type-info {
        flex: 1;

        .type-label {
          display: block;
          font-size: 16px;
          color: $label-primary;
          font-weight: 600;
          margin-bottom: 4px;
          letter-spacing: -0.2px;
        }

        .type-desc {
          font-size: 13px;
          color: $label-secondary;
          font-weight: 400;
          opacity: 0.8;
        }
      }

      .check-mark {
        font-size: 16px;
        color: $system-blue;
        font-weight: bold;
      }
    }
  }
}

// 响应式设计
@media (max-width: 750rpx) {
  .materials-filter {
    .filter-content {
      padding: 16px;
    }

    .search-input-wrapper {
      flex-direction: column;
      gap: 12px !important;

      .search-type-selector {
        min-width: auto;
        width: 100%;
      }

      .search-button {
        width: 100% !important;
        height: 44px;
      }
    }
  }
}

// 暗色模式支持
@media (prefers-color-scheme: dark) {
  .materials-filter {
    background: #2c2c2e;

    .filter-header {
      background: rgba(0, 122, 255, 0.15);
      border-bottom-color: rgba(0, 122, 255, 0.2);
    }

    .search-type-selector {
      background: #48484a;
      border-color: #48484a;

      .search-type-text {
        color: #ffffff;
      }
    }

    .search-type-list {
      background: #2c2c2e;

      .search-type-item {
        border-bottom-color: #48484a;

        &:active {
          background: #48484a;
        }

        .type-label {
          color: #ffffff;
        }

        .type-desc {
          color: #8e8e93;
        }
      }
    }
  }
}

// 全局样式确保搜索类型弹窗在最上层
:global(.search-type-popup .wd-popup) {
  z-index: 9999 !important;
}

:global(.search-type-popup .wd-popup__mask) {
  z-index: 9998 !important;
}

:global(.search-type-popup .wd-popup__content) {
  z-index: 9999 !important;
}
</style>
